package cn.edu.scau.cmi.chenyuesong.hibernate.dao;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.chenyuesong.hibernate.entity.Student;
import cn.edu.scau.cmi.chenyuesong.hibernate.utils.HibernateUtils;

public class StudentDAO {
	private static final Logger log = LoggerFactory.getLogger(StudentDAO.class);
	
	public void addstu(Student student){
		log.debug("saving Student instance");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			session.save(student);
			log.debug("save successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("save failed", re);
			transaction.rollback();
		}
    }
	
	public void delstu(Student student){
		log.debug("delete Student instance");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			session.remove(student);
			log.debug("delete successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("delete failed", re);
			transaction.rollback();
		}
    }
	
	public void updstu(Student student){
		log.debug("update Student instance");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			session.update(student);
			log.debug("update successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("update failed", re);
			transaction.rollback();
		}
    }
	
	public List<Student> getAllStu() {
		List<Student> students = new ArrayList<Student>();
		log.debug("get all Student");
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			Query query = session.createQuery("from Student");
			students = query.list();
			log.debug("get all Student successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("get all Student failed", re);
			transaction.rollback();
		}
		return students;
	}
	
	public Student getStu(Integer id) {
		log.debug("get Student");
		Student student = new Student();
		Session session = null;
		Transaction transaction = null;
		try {
			session = HibernateUtils.getSession();
			transaction = session.beginTransaction();
			student = (Student) session.get("cn.edu.scau.cmi.cheyuesong.hibernate.entity.Student",id);
			log.debug("get Student successful");
			transaction.commit();
		}catch(RuntimeException re) {
			log.error("get Student failed", re);
			transaction.rollback();
		}
		return student;
	}
}
